﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LoanCalculator : MonoBehaviour
{

    // Model: loan parameters
    private float loanAmount = 0f; // 贷款金额
    private float annualInterestRate = 0f; // 年利率
    private int loanTermYears = 0; // 贷款年限
    private float monthlyPayment = 0f; // 每月还款金额
    private float monthlyPrincipal = 0f; // 每月本金
    private float monthlyInterest = 0f; // 每月利息

    // System Handlers
    void Start()
    {
        ResetCalculator();
    }

    // View to render entities / models
    void OnGUI()
    {
        GUI.Box(new Rect(210, 25, 300, 320), "贷款计算器");

        // 输入字段
        GUI.Label(new Rect(230, 50, 100, 20), "贷款金额：");
        string loanAmountString = GUI.TextField(new Rect(330, 50, 150, 20), loanAmount.ToString());
        float.TryParse(loanAmountString, out loanAmount);

        GUI.Label(new Rect(230, 80, 100, 20), "年利率 (%)：");
        string interestRateString = GUI.TextField(new Rect(330, 80, 150, 20), annualInterestRate.ToString());
        float.TryParse(interestRateString, out annualInterestRate);

        GUI.Label(new Rect(230, 110, 100, 20), "贷款年限：");
        string loanTermString = GUI.TextField(new Rect(330, 110, 150, 20), loanTermYears.ToString());
        int.TryParse(loanTermString, out loanTermYears);

        // 计算按钮
        if (GUI.Button(new Rect(310, 150, 100, 30), "计算"))
        {
            CalculateMonthlyPayment();
        }

        // 显示结果
        GUI.Label(new Rect(230, 200, 250, 20), "每月还款金额： " + monthlyPayment.ToString("F2"));
        GUI.Label(new Rect(230, 230, 250, 20), "每月本金： " + monthlyPrincipal.ToString("F2"));
        GUI.Label(new Rect(230, 260, 250, 20), "每月利息： " + monthlyInterest.ToString("F2"));

        // 重置按钮
        if (GUI.Button(new Rect(310, 290, 100, 30), "重置"))
        {
            ResetCalculator();
        }
    }

    // Components / controls
    void ResetCalculator()
    {
        loanAmount = 0f;
        annualInterestRate = 0f;
        loanTermYears = 0;
        monthlyPayment = 0f;
        monthlyPrincipal = 0f;
        monthlyInterest = 0f;
    }

    void CalculateMonthlyPayment()
    {
        if (loanAmount <= 0 || annualInterestRate <= 0 || loanTermYears <= 0)
        {
            monthlyPayment = 0f;
            monthlyPrincipal = 0f;
            monthlyInterest = 0f;
            return;
        }

        float monthlyInterestRate = annualInterestRate / 100 / 12; // 月利率
        int totalMonths = loanTermYears * 12; // 总还款期数

        // 等额本息计算公式
        monthlyPayment = loanAmount * monthlyInterestRate * Mathf.Pow(1 + monthlyInterestRate, totalMonths)
                         / (Mathf.Pow(1 + monthlyInterestRate, totalMonths) - 1);

        // 计算每月本金和利息
        monthlyPrincipal = loanAmount / (float)totalMonths;
        monthlyInterest = monthlyPayment - monthlyPrincipal;
    }
}